<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\LoginRequest;
use App\Http\Resources\UserResource;
use App\Models\Setting;
use Illuminate\Support\Facades\Auth;
use Jenssegers\Agent\Agent;

class LoginController extends Controller
{
    /**
     * 登录
     * @param LoginRequest $request
     * @return mixed
     */
    public function login(LoginRequest $request)
    {
        $token = Auth::attempt($request->only(['name', 'password']));

        if ($token) {
            $user = $this->user();

            if ($user->isLocked()) {
                return $this->failed('该用户已被冻结, 请联系管理员解除', 401);
            }

            // 更新登录时间
            $geo = geoip($request->ip())->toArray();
            $user->login_time = now();
            $user->login_city = $geo['city'] ?? '';
            $user->save();

            return $this->setStatusCode(201)->success([
                'token' => 'Bearer ' . $token,
                'user' => new UserResource($user),
                'config' => Setting::pluck('value', 'key')->toArray(),
                'menus' => $user->getMenus()
            ]);
        }

        return $this->failed('用户名或密码错误', 401);
    }

    /**
     * 退出登录
     * @return mixed
     */
    public function logout()
    {
        Auth::logout();
        return $this->success('成功退出登录');
    }
}
